import { createRouter, createWebHistory } from 'vue-router'
import Login from "@/views/Login.vue";
import ChatView from "@/views/ChatView.vue"; // 引入聊天页面组件

const routes = [
  {
    path: '/',
    redirect: '/login' // 默认重定向到登录页
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/chatView', // 确保路径正确
    name: 'chatView',
    component: ChatView,
    meta: { requiresAuth: true } // 需要登录才能访问
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫：检查用户是否登录
// router/index.js
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  console.log(`导航到: ${to.path}, token: ${token}`);

  if (to.meta.requiresAuth && !token) {
    console.log("未登录，跳转到 /login");
    next("/login");
  } else {
    // 如果用户已登录且尝试访问登录页，直接跳转到主页
    if (to.path === "/login" && token) {
      console.log("已登录，不允许访问登录页，跳转到 /chatview");
      next("/chatview");
    } else {
      console.log("已登录，允许访问");
      next();
    }
  }
});

export default router